package controllers

import (
	"fmt"
	"odooapp/app/odooapi"

	"github.com/revel/revel"
)

type OdooQuotation struct {
	*revel.Controller
}

func (c OdooQuotation) SearchRead() revel.Result {
	respData := make(map[string]interface{})
	client, jsonParams, err := GetAliveOdooClient(c.Params)
	model, ok := jsonParams["model"]
	if !ok {
		respData["isSuccess"] = false
		respData["errMsg"] = "Error in parameters, please specify model"
		return c.RenderJSON(respData)
	}

	if err != nil {
		respData["isSuccess"] = false
		respData["errMsg"] = err.Error()
		return c.RenderJSON(respData)
	}
	fmt.Println(client.Auth.Result.UID)
	//read sales order
	if sales, err := client.SearchRead(
		model.(string),
		odooapi.List{
			odooapi.List{"user_id", "=", client.Auth.Result.UserContext["uid"]},
		},
		[]string{"name", "create_date"},
	); err != nil {
		respData["isSuccess"] = false
		respData["errMsg"] = err.Error()
		return c.RenderJSON(respData)
	} else {
		respData["sales"] = sales
	}
	respData["isSuccess"] = true
	return c.RenderJSON(respData)
}

func (c OdooQuotation) PageSearchRead() revel.Result {
	respData := make(map[string]interface{})
	client, jsonParams, err := GetAliveOdooClient(c.Params)
	model, ok := jsonParams["model"]
	if !ok {
		respData["isSuccess"] = false
		respData["errMsg"] = "Error in parameters, please specify model"
		return c.RenderJSON(respData)
	}
	if err != nil {
		respData["isSuccess"] = false
		respData["errMsg"] = err.Error()
		return c.RenderJSON(respData)
	}
	pageInfo := &odooapi.PageInfo{}
	if limit, ok := jsonParams["limit"]; ok {
		pageInfo.Limit = int(limit.(float32))
	}

	if offeset, ok := jsonParams["offset"]; ok {
		pageInfo.Offset = int(offeset.(float32))
	}

	if sort, ok := jsonParams["sort"]; ok {
		pageInfo.Sort = sort.(string)
	}

	//read sales order
	//model, e.g. "product.template"
	if sales, err := client.SearchReadPages(
		model.(string),
		odooapi.List{
			odooapi.List{"sale_ok", "=", true},
		},
		[]string{"name", "create_date"},
		pageInfo,
	); err != nil {
		respData["isSuccess"] = false
		respData["errMsg"] = err.Error()
		return c.RenderJSON(respData)
	} else {
		respData["sales"] = sales
	}
	respData["isSuccess"] = true
	return c.RenderJSON(respData)
}
